const express = require('express')
const router = express.Router()

// Lazy require to avoid crashing if env not set in non-TRTC flows
let TLSSigAPIv2
try { TLSSigAPIv2 = require('tls-sig-api-v2') } catch (_) {}

const SDKAPPID = 20027355
const SECRETKEY = process.env.TRTC_SECRET_KEY

router.get('/trtc/userSig', (req, res) => {
  try {
    const userId = String(req.query.userId || '').trim()
    if (!userId) return res.status(400).json({ error: 'missing userId' })
    if (!TLSSigAPIv2) return res.status(500).json({ error: 'missing tls-sig-api-v2' })
    if (!SECRETKEY) return res.status(500).json({ error: 'missing TRTC_SECRET_KEY' })

    const api = new TLSSigAPIv2.Api(SDKAPPID, SECRETKEY)
    const expire = 3600
    const userSig = api.genUserSig(userId, expire)
    res.json({ sdkAppId: SDKAPPID, userId, userSig, expire })
  } catch (e) {
    res.status(500).json({ error: e?.message || 'gen userSig failed' })
  }
})

module.exports = router


